<template>
  <div class="login">
    <h2>Login</h2>
    <form @submit.prevent="handregister">
      <div class="form-group">
        <label for="username">Username:</label>
        <input type="text" id="username" v-model="username" required />
      </div>
      <div class="form-group">
        <label for="password">Password:</label>
        <input type="password" id="password" v-model="password" required />
      </div>
      <div class="form-group">
        <label for="phone">Phone:</label>
        <input type="text" id="phone" v-model="phone" required>
      </div>
      <div class="from-group">
        <label for="email">Email:</label>
        <input type="text" id="email" v-model="email" required>
      </div>
      <button type="submit">Login</button>
      <p v-if="error" class="error">{{ error }}</p>
    </form>
  </div>
</template>

<script >
import axios from 'axios';
export default {
  name:'Register',
  data() {
    return {
      username: '',
      password: '',
      phone: '',
      email: '',
      error: null,
    };
  },
  methods: {
    async handregister() {
      try {
        const response = await axios.post('http://localhost:8080/api/register', {
          username: this.username,
          password: this.password,
          phone: this.phone,
          email: this.email
        });
        // 将用户名存储在本地存储中
        localStorage.setItem('username', this.username);
        // 返回主页
        this.$router.push('/');
      } catch (error) {
        if (error.response && error.response.status === 401) {
          this.error = 'Invalid credentials';
        } else {
          this.error = 'An error occurred during register';
        }
      }
    },
  },

};
</script>



<style scoped>
.login {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.form-group {
  margin-bottom: 15px;
}

.error {
  color: red;
}
</style>